엘릭서에서는 데이터 처리가 두 가지 명확한 철학을 따릅니다: 탐욕적 (즉각적)이고 게으른. 이 둘 사이의 균형을 이해하는 것은 메모리 효율성과 시스템 안정성에 매우 중요합니다.
1. 열거 가능한 프로토콜
기술적으로, 반복할 수 있는 것들은 열거 가능한 프로토콜을 구현한다고 말합니다. 이 공통 계약 덕분에 다양한 데이터 구조가 동일한 함수 집합을 사용할 수 있습니다.
2. 탐욕적 모듈과 게으른 모듈
이때 Enum 모듈은 탐욕적입니다. 이는 컬렉션의 모든 내용을 즉시 소비할 수 있으며, 파이프라인의 각 단계에서 중간 리스트를 생성합니다. 반면, Stream 모듈은 게으릅니다. 다음 값은 필요할 때만 계산됩니다.
3. 사양과 결과의 차이
스트림 값은 Stream 값 우리가 의도한 사양일 뿐이며, 실제 결과는 아닙니다. 스트림은 열거 가능하고 조합 가능하며, 스트림을 '즉각적' 작업(예: `Enum.to_list/1`)으로 전달하기 전까지는 작업을 실행하지 않고 변환을 쌓을 수 있습니다. `Enum.to_list/1`처럼.
4. 철학의 순수성
기능적 접근과 객체지향적 접근을 혼용하면 기능적 방식의 장점이 희석됩니다. 예측 가능성 면에서 명령형 반복문보다 선언적 변환을 우선하세요.
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What happens when you pass a collection to the
Enum module?It creates a lazy recipe for later execution.
It potentially consumes all contents immediately and returns a result.
It returns a Stream struct containing the function logic.
It converts the data into an object-oriented class.
✅ Correct!
Correct! Enum is greedy, meaning it realizes the entire result immediately.❌ Incorrect
That describes the Stream module. Enum is 'greedy' and processes data immediately.QUESTION 2
Which statement best describes a 'Stream' in Elixir?
A realized list of integers.
A specification of intended work, not the result itself.
A faster version of Enum for small lists.
A specific type of Map used for key-value storage.
✅ Correct!
Exactly. Streams are recipes or specifications that define work to be done later.❌ Incorrect
Streams do not hold results; they hold the logic to generate results on demand.QUESTION 3
Why would you choose Stream over Enum for a 10GB text file?
Enum cannot read files.
Stream executes faster for small datasets.
Stream processes data line-by-line, preventing memory exhaustion.
Stream automatically sorts the file contents.
✅ Correct!
Yes! Lazy processing avoids loading the whole file into RAM at once.❌ Incorrect
Enum would attempt to load the entire 10GB into memory, likely crashing the VM.QUESTION 4
According to the lesson logic, what is a danger of mixing functional and OO paradigms?
It makes the code run significantly faster.
It dilutes the benefits of the functional approach.
It is required for the Enumerable protocol.
It allows Elixir to run on the JVM.
✅ Correct!
Right. Paradigmatic purity helps maintain clarity and functional predictability.❌ Incorrect
Actually, the text states it dilutes the benefits of functional programming.QUESTION 5
What is the requirement for a data type to be usable with Enum and Stream modules?
It must be a binary string.
It must implement the Enumerable protocol.
It must be smaller than 1MB.
It must be a recursive Keyword list.
✅ Correct!
Correct! The Enumerable protocol is the universal interface for collections.❌ Incorrect
Any structure implementing the Enumerable protocol can be used.Module Challenge: Prime Sequences & String Cleaning
Applying greedy and lazy transformations to complex data tasks.
You are tasked with generating mathematical sequences and cleaning messy user input. You must use list comprehensions and high-level string functions to achieve efficient results.
Q
1. Using your previously written 'span' function (which returns a list from 2 to n), use list comprehensions to return a list of the prime numbers from 2 to n.
Solution:
Model Solution: elixir def primes_up_to(n) do range = span(2, n) for x <- range, is_prime?(x), do: x end defp is_prime?(2), do: true defp is_prime?(n) when n < 2, do: false defp is_prime?(n) do Enum.all?(2..round(:math.sqrt(n)), fn x -> rem(n, x) != 0 end) end This uses the span function as a generator and a filter predicate to identify primes.
Model Solution: elixir def primes_up_to(n) do range = span(2, n) for x <- range, is_prime?(x), do: x end defp is_prime?(2), do: true defp is_prime?(n) when n < 2, do: false defp is_prime?(n) do Enum.all?(2..round(:math.sqrt(n)), fn x -> rem(n, x) != 0 end) end This uses the span function as a generator and a filter predicate to identify primes.
Q
2. [Writing Task] Write a function to capitalize the sentences in a string. Each sentence is terminated by a period and a space ('. '). Assume 150-word output capacity for the logic explanation.
Solution:
To capitalize sentences in a string where casing is currently random, follow these steps (approx 150 words of logic): First, use `String.split(input, ". ")` to break the string into a list of individual sentences. Note that the delimiter is lost in the split. Second, apply a transformation function to each element using `Enum.map`. Inside this map, use `String.capitalize/1`, which lowercases the whole string and then capitalizes the very first character. This ensures 'tHe dOg.' becomes 'The dog.'. Finally, use `Enum.join(". ")` to re-attach the sentences with the proper punctuation. Example code: elixir def capitalize_sentences(str) do str |> String.split(". ") |> Enum.map(&String.capitalize/1) |> Enum.join(". ") end
To capitalize sentences in a string where casing is currently random, follow these steps (approx 150 words of logic): First, use `String.split(input, ". ")` to break the string into a list of individual sentences. Note that the delimiter is lost in the split. Second, apply a transformation function to each element using `Enum.map`. Inside this map, use `String.capitalize/1`, which lowercases the whole string and then capitalizes the very first character. This ensures 'tHe dOg.' becomes 'The dog.'. Finally, use `Enum.join(". ")` to re-attach the sentences with the proper punctuation. Example code: elixir def capitalize_sentences(str) do str |> String.split(". ") |> Enum.map(&String.capitalize/1) |> Enum.join(". ") end
Q
3. What occurs when you modify a printable character function example to use '99.0' (a float) where a charlist is expected?
Solution:
In Elixir, a charlist is a list of integers. If you provide '99.0', the system will raise a FunctionClauseError or a type error because '99.0' is a floating-point number, not an integer representing a codepoint. Charlist processing functions rely on the integer values (like 99 for 'c') to determine printability; floats do not satisfy the Enumerable protocol for lists or the bitstring requirements for binaries in this context.
In Elixir, a charlist is a list of integers. If you provide '99.0', the system will raise a FunctionClauseError or a type error because '99.0' is a floating-point number, not an integer representing a codepoint. Charlist processing functions rely on the integer values (like 99 for 'c') to determine printability; floats do not satisfy the Enumerable protocol for lists or the bitstring requirements for binaries in this context.